package com.atguigu.msmservice.controller;

/*
 * @ClassName MsmController
 * @author  忘忧君
 * @Description
 * @Version 1.0
 */

import com.aliyuncs.utils.StringUtils;
import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.MailRequest;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
@Api(value = "发送邮件接口",tags = {"发送邮件接口"})
// @CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 发送短信方法
    @ApiOperation(value = "发送短信")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        String code = redisTemplate.opsForValue().get(phone);

        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        boolean isSend = msmService.send(param, phone);
        if (isSend){
            // 将发送的验证码存入redis中
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("短信发送失败");
        }
    }

    @ApiOperation(value = "发送邮件")
    @GetMapping("/simple/{email}")
    public R SendSimpleMessage(@PathVariable String email) {

        String code = redisTemplate.opsForValue().get(email);

        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }

        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        boolean isSend = msmService.sendSimpleMail(param, email);
        if (isSend){
            // 将发送的验证码存入redis中
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("邮件发送失败");
        }
    }

}
